#!/bin/bash -x

kata_coco_top_dir="$HOME/workspace/CoCo/"

kata_containers_repo_url="https://gitee.com/hanliyang-kata-coco/kata-containers.git"
kata_containers_repo_branch="3.13.0-hygon"
kata_containers_repo_dir="${kata_coco_top_dir}/kata-containers"

if [ ! -e ${kata_containers_repo_dir} ]; then
  git clone ${kata_containers_repo_url} \
    -b ${kata_containers_repo_branch} \
    ${kata_containers_repo_dir}
fi

# check and install yq if not exist
echo "Check and Install yq"
command yq > /dev/null
if [ $? -ne 0 ]; then
  DEBUG="y" ${kata_containers_repo_dir}/ci/install_yq.sh
  echo 'export PATH=$PATH:$HOME/go/bin/' >> $HOME/.profile
  source $HOME/.profile
fi

qemu_repo_url="https://gitee.com/openeuler/qemu.git"
qemu_repo_branch="qemu-8.2.0"
qemu_repo_commit="6a18d7d50dc49eb86ebb74a77b2c86d8ea09a906"
qemu_repo_dir=/dev/shm/openeuler-qemu

packaging_dir="$(realpath ${kata_containers_repo_dir}/tools/packaging)"

if [ ! -e ${qemu_repo_dir} ]; then
  git clone ${qemu_repo_url} \
    -b ${qemu_repo_branch} \
    ${qemu_repo_dir}
  pushd ${qemu_repo_dir}
  git reset --hard ${qemu_repo_commit}
  popd
fi

install_kata_qemu_deps () {
  echo "Install kata qemu dependencies"
  sudo apt install -y python3-pip ninja-build \
    libglib2.0-dev libaio-dev \
    libseccomp-dev libcap-ng-dev

  if [ ! -e ${kata_coco_top_dir}/liburing ]; then
    git clone https://github.com/axboe/liburing.git \
      ${kata_coco_top_dir}/liburing
  fi
  pushd ${kata_coco_top_dir}/liburing
  ./configure && make && sudo make install
  popd # .../liburing
}

install_kata_qemu_deps

build_install_qemu () {
  echo "Build and Install kata qemu"
  pushd ${qemu_repo_dir}

  source ${kata_containers_repo_dir}/tools/packaging/scripts/lib.sh

  PREFIX="/opt/kata/" "$packaging_dir/scripts/configure-hypervisor.sh" -s kata-qemu > kata.cfg
  eval ./configure "$(cat kata.cfg)"
  make -j $(nproc --ignore=1)
  sudo -E make install

  popd # ${qemu_repo_dir}
}

build_install_qemu
